import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { useUserStore } from '@/store/modules/user'
import { toast, showConfirm, tansParams } from '@/utils/common'

let timeout = 60000 // 增加到60秒，处理包含大量数据的请求

// 创建通用请求函数
const createRequest = (baseUrl) => {
  return (requestConfig) => {
    // 是否需要设置 token
    const isToken = (requestConfig.headers || {}).isToken === false
    requestConfig.header = requestConfig.header || {}
    if (getToken() && !isToken) {
      requestConfig.header['Authorization'] = 'Bearer ' + getToken()
    }
    // get请求映射params参数
    if (requestConfig.params) {
      let url = requestConfig.url + '?' + tansParams(requestConfig.params)
      url = url.slice(0, -1)
      requestConfig.url = url
    }
    return new Promise((resolve, reject) => {
      uni.request({
          method: requestConfig.method || 'get',
          timeout: requestConfig.timeout || timeout,
          url: requestConfig.baseUrl || baseUrl + requestConfig.url,
          data: requestConfig.data,
          header: requestConfig.header,
          dataType: 'json'
        }).then(response => {
          const res = response
          const code = res.data.code || 200
          const msg = res.data.msg || errorCode[code] || errorCode['default']
          if (code === 401) {
            showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
              if (res.confirm) {
                useUserStore().logOut().then(res => {
                  uni.reLaunch({ url: '/pages/pc/login' })
                })
              }
            })
            reject('无效的会话，或者会话已过期，请重新登录。')
          } else if (code === 500) {
            // 500错误不显示toast，避免在云服务中显示错误信息
            // toast(msg)
            reject(msg)
          } else if (code !== 200) {
            toast(msg)
            reject(msg)
          }
          resolve(res.data)
        })
        .catch(error => {
          let { message } = error
          if (message === 'Network Error') {
            message = '后端接口连接异常'
          } else if (message && message.includes('timeout')) {
            message = '系统接口请求超时'
          } else if (message && message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常'
          }
          toast(message)
          reject(error)
        })
    })
  }
}

// 创建Ten Framework专用请求函数
const createTenRequest = (baseUrl) => {
  return (requestConfig) => {
    // console.log('tenRequest called with config:', requestConfig)
    // console.log('baseUrl:', baseUrl)
    
    // 是否需要设置 token
    const isToken = (requestConfig.headers || {}).isToken === false
    requestConfig.header = requestConfig.header || {}
    if (getToken() && !isToken) {
      requestConfig.header['Authorization'] = 'Bearer ' + getToken()
    }
    // get请求映射params参数
    if (requestConfig.params) {
      let url = requestConfig.url + '?' + tansParams(requestConfig.params)
      url = url.slice(0, -1)
      requestConfig.url = url
    }
    
    const finalUrl = requestConfig.baseUrl || baseUrl + requestConfig.url
    console.log('Final request URL:', finalUrl)
    console.log('Request data:', requestConfig.data)
    
    return new Promise((resolve, reject) => {
      uni.request({
          method: requestConfig.method || 'get',
          timeout: requestConfig.timeout || timeout,
          url: finalUrl,
          data: requestConfig.data,
          header: requestConfig.header,
          dataType: 'json'
        }).then(response => {
          console.log('tenRequest response:', response)
          const res = response
          const code = res.data.code
          const msg = res.data.msg || 'Unknown error'
          
          // Ten Framework: code="0"表示成功
          if (code === "0") {
            resolve(res.data)
          } else {
            toast(msg)
            reject(code)
          }
        })
        .catch(error => {
          console.error('tenRequest error:', error)
          let { message } = error
          if (message === 'Network Error') {
            message = '后端接口连接异常'
          } else if (message && message.includes('timeout')) {
            message = '系统接口请求超时'
          } else if (message && message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常'
          }
          toast(message)
          reject(error)
        })
    })
  }
}

// 后台API请求（默认）
const request = createRequest(config.baseUrl)

// Ten Framework语音服务请求 - 使用专用处理逻辑
export const tenRequest = createTenRequest(config.tenFrameworkUrl)

export default request
